package com.szq.day39.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.szq.day39.Exception.BusinessException;
import com.szq.day39.constants.Constants;
@Controller
public class FileController {
	@RequestMapping("upload")
	public void upload(PrintWriter out, MultipartHttpServletRequest request) throws BusinessException{
	try {
		MultipartFile file = request.getFile("upload");
		String fileName =UUID.randomUUID().toString();
		File newFile = new File(Constants.FILE_PATH+fileName);
		file.transferTo(newFile);
			

		String callback = request.getParameter("CKEditorFuncNum");   
	    out.println("<script type=\"text/javascript\">");  
	    out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" + request.getContextPath() + "/show/"+ fileName + "','')");   
	    out.println("</script>");
	        
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E00C06");
		}
	}
	@RequestMapping("/show/{fileName}")
	public void show(@PathVariable("fileName") String fileName,HttpServletResponse response) throws BusinessException{
		File file = new File(Constants.FILE_PATH+fileName);
		if(file.exists()){
			try {
				FileInputStream fis = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte [] b = new byte[1024];
				int len=0;
				while((len=fis.read(b))!=-1){
					os.write(b, 0, len);
				}
				fis.close();
			} catch (Exception e) {
				throw new BusinessException("E00C08");
			}
			
		}else{
			throw new BusinessException("E00C07");
		}
	}

}
